package com.duoduo.admin.service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.duoduo.admin.api.dto.SysRoleMenuDTO;
import com.duoduo.admin.entity.SysRoleMenu;
import com.duoduo.admin.repository.SysRoleMenuRepository;
import com.duoduo.common.jpa.service.CommonService;

import jakarta.persistence.criteria.Predicate;

@Service
public class SysRoleMenuService extends CommonService<SysRoleMenuDTO, SysRoleMenu, SysRoleMenu>{

	@Autowired
	private SysRoleMenuRepository sysRoleMenuRepository;
	@Override
	public Specification<SysRoleMenu> getWhere(SysRoleMenuDTO request) {
		return (root, query, cb) -> {
			final List<Predicate> predicate = new ArrayList<Predicate>();
			if(request.getRoleId()!=null) {
				predicate.add(cb.equal(root.get("role_id"), request.getRoleId()));	
			}
			if(request.getMenuId()!=null) {
				predicate.add(cb.equal(root.get("menu_id"), request.getMenuId()));	
			}
			
			final Predicate[] pre = new Predicate[predicate.size()];
			return query.where(predicate.toArray(pre)).getRestriction();
		};
	}

	@Transactional
	public void saveRoleMenus(Long roleId, List<Long> menuIds) {
		sysRoleMenuRepository.deleteByRoleId(roleId);
		List<SysRoleMenu> list = menuIds.stream().map(p ->{
			SysRoleMenu sysRoleMenu = new SysRoleMenu();
			sysRoleMenu.setRoleId(roleId);
			sysRoleMenu.setMenuId(p);
			return sysRoleMenu;
		}).toList();
		sysRoleMenuRepository.saveAll(list);
	}

}
